package io.github.javpower.imagerex.actuator;

import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;

@Component
@Endpoint(id = "accesslog")
public class AccessLogEndpoint {

    // 保存最近 100 条访问记录
    private final LinkedList<AccessRecord> logs = new LinkedList<>();
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final Logger accessLogger = LoggerFactory.getLogger("ACCESS_LOG");

    public void addLog(String name,String ip, int port, String path) {
        if (!path.startsWith("/api/")) {
            return; // 只记录 /api/ 路径
        }
        logs.add(new AccessRecord(name,LocalDateTime.now(), ip,port, path));
        // ✅ 写到 access.log
        accessLogger.info("name={}, ip={}, port={}, path={}, time={}",
                name,LocalDateTime.now(), ip, port, path);
    }

    @ReadOperation
    public List<AccessRecord> getLogs() {
        return logs;
    }

    public static class AccessRecord {
        private String name;

        private String time;
        private String ip;
        private int port;
        private String path;
        public AccessRecord(String name,LocalDateTime time, String ip, int port, String path) {
            this.name=name;
            this.time = time.format(formatter); // 格式化时间
            this.ip = ip;
            this.port = port;
            this.path = path;
        }
        public String getTime() { return time; }
        public String getIp() { return ip; }
        public int getPort() { return port; }
        public String getPath() { return path; }
        public String getName() {return name;}
    }
}